﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

namespace JTT.Dev.Toolkit
{
    /// <summary>
    /// XML处理空间
    /// </summary>
    namespace XML
    {
        /// <summary>
        /// XML辅助类
        /// </summary>
        public static class XMLHelper
        {

            /// <summary>
            /// XML序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="_Object"></param>
            /// <returns></returns>
            public static String ObjectToXml<T>(this T _Object)
            {
                XmlSerializer MyXmlSerializer = new XmlSerializer(typeof(T));
                XmlSerializerNamespaces MyXmlSerializerNamespaces = new XmlSerializerNamespaces();
                MyXmlSerializerNamespaces.Add("", "");
                XmlWriterSettings MyXmlWriterSettings = new XmlWriterSettings();
                MyXmlWriterSettings.OmitXmlDeclaration = true;
                StringBuilder MyStringBuilder = new StringBuilder();
                XmlWriter MyXmlWriter = XmlWriter.Create(MyStringBuilder, MyXmlWriterSettings);
                MyXmlSerializer.Serialize(MyXmlWriter, _Object, MyXmlSerializerNamespaces);
                return MyStringBuilder.ToString();
            }

            /// <summary>
            /// XML反序列化
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="xmlString"></param>
            /// <returns></returns>
            public static T XmlToObject<T>(this String _XMLString)
            {
                using (StringReader TempMemoryStream = new StringReader(_XMLString))
                {
                    XmlSerializer MyXmlSerializer = new XmlSerializer(typeof(T));
                    return (T)MyXmlSerializer.Deserialize(TempMemoryStream);
                }
            }
        }      
    }
}
